<template>
  <div class="questionnaire-detail" v-loading="loading">
    <el-form ref="form" :model="questionnaire" label-width="100px">
      <el-form-item label="问卷标题" required>
        <el-input v-model="questionnaire.title" placeholder="请输入问卷标题"></el-input>
      </el-form-item>
      <el-form-item label="问卷描述">
        <el-input v-model="questionnaire.description" type="textarea" placeholder="请输入问卷描述"></el-input>
      </el-form-item>

      <div class="questions-container">
        <div class="questions-header">
          <h3>问题列表</h3>
          <el-button type="primary" @click="addQuestion">添加问题</el-button>
        </div>

        <el-card v-for="(question, index) in questionnaire.questions" :key="index" class="question-card">
          <template #header>
            <div class="question-header">
              <span>问题 {{ index + 1 }}</span>
              <div class="question-actions">
                <el-button link type="primary" @click="moveQuestion(index, -1)" :disabled="index === 0">
                  上移
                </el-button>
                <el-button link type="primary" @click="moveQuestion(index, 1)" 
                          :disabled="index === questionnaire.questions.length - 1">
                  下移
                </el-button>
                <el-button link type="danger" @click="removeQuestion(index)">删除</el-button>
              </div>
            </div>
          </template>

          <el-form-item label="题目" required>
            <el-input v-model="question.title" placeholder="请输入题目"></el-input>
          </el-form-item>

          <el-form-item label="题目类型" required>
            <el-select v-model="question.type" placeholder="请选择题目类型">
              <el-option label="单选题" :value="1"></el-option>
              <el-option label="多选题" :value="2"></el-option>
              <el-option label="填空题" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否必填">
            <el-switch v-model="question.required" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>

          <template v-if="question.type !== 3">
            <div class="options-container">
              <div class="options-header">
                <h4>选项列表</h4>
                <el-button type="primary" link @click="addOption(question)">添加选项</el-button>
              </div>

              <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
                <el-input v-model="option.content" placeholder="请输入选项内容">
                  <template #append>
                    <el-button type="danger" link @click="removeOption(question, optionIndex)">删除</el-button>
                  </template>
                </el-input>
              </div>
            </div>
          </template>
        </el-card>
      </div>

      <div class="form-actions">
        <el-button type="primary" @click="handleSave">保存问卷</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getQuestionnaire, saveDetail } from '@/api/questionnaire'

const route = useRoute()
const router = useRouter()
const questionnaireId = route.params.id
const loading = ref(false)
const questionnaire = ref({
  title: '',
  description: '',
  questions: []
})

const loadQuestionnaire = async () => {
  if (!questionnaireId) {
    // 新增问卷时初始化空数据
    questionnaire.value = {
      title: '',
      description: '',
      questions: []
    }
    return
  }

  loading.value = true
  try {
    const res = await getQuestionnaire(questionnaireId)
    if (res.code === 200) {
      questionnaire.value = res.data
      if (!questionnaire.value.questions) {
        questionnaire.value.questions = []
      }
    } else {
      ElMessage.error(res.message || '加载问卷失败')
    }
  } catch (error) {
    console.error('加载问卷失败:', error)
    ElMessage.error('加载问卷失败')
  } finally {
    loading.value = false
  }
}

const addQuestion = () => {
  questionnaire.value.questions.push({
    title: '',
    type: 1,
    required: 1,
    sort: questionnaire.value.questions.length,
    options: []
  })
}

const removeQuestion = (index) => {
  questionnaire.value.questions.splice(index, 1)
}

const moveQuestion = (index, direction) => {
  const newIndex = index + direction
  if (newIndex < 0 || newIndex >= questionnaire.value.questions.length) {
    return
  }
  const questions = questionnaire.value.questions
  const temp = questions[index]
  questions[index] = questions[newIndex]
  questions[newIndex] = temp
  questions.forEach((q, i) => q.sort = i)
}

const addOption = (question) => {
  if (!question.options) {
    question.options = []
  }
  question.options.push({
    content: '',
    sort: question.options.length
  })
}

const removeOption = (question, index) => {
  question.options.splice(index, 1)
}

const handleSave = async () => {
  if (!questionnaire.value.title) {
    ElMessage.warning('请输入问卷标题')
    return
  }

  try {
    const res = await saveDetail(questionnaireId || 'new', questionnaire.value)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      router.push('/admin/questionnaire')
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存问卷失败:', error)
    ElMessage.error('保存失败')
  }
}

onMounted(() => {
  loadQuestionnaire()
})
</script>

<style scoped>
.questionnaire-detail {
  padding: 20px;
}
.questions-container {
  margin: 20px 0;
}
.questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.question-card {
  margin-bottom: 20px;
}
.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.options-container {
  margin-top: 20px;
}
.options-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.option-item {
  margin-bottom: 10px;
}
.form-actions {
  margin-top: 20px;
  text-align: center;
}
</style> 